package l.l.w.leetcode.SwapNodesInPairs;

/**
 * Created by llw on 2017/11/3.
 */
public class SwapNodesInPairs {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)return head;
        ListNode result,cur,next,pre;
        result = head.next;
        cur = result.next;
        pre = head;
        result.next = head;
        head.next = cur;
        while(cur != null){
            next = cur.next;
            if(next == null) break ;
            pre.next = next;
            cur.next = next.next;
            next.next = cur;

            pre = cur;
            cur = cur.next;
        }
        return result;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        ListNode n6 = new ListNode(6);
        ListNode n7 = new ListNode(7);
        n6.next = n7;
        n5.next = n6;
        n4.next = n5;
        n3.next = n4;
        n2.next = n3;
        head.next = n2;
        ListNode result = new SwapNodesInPairs().swapPairs(head);
        System.out.println(result);
    }
}
class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
}
